package per.turtle.common.security.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.RequiredArgsConstructor;
import per.turtle.common.core.constant.CacheConstants;
import per.turtle.common.core.utils.SecurityUtils;
import per.turtle.common.core.utils.ServletUtils;
import per.turtle.common.redis.service.RedisService;
import per.turtle.system.dto.LoginUser;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author turtle
 */
@RequiredArgsConstructor
public class TokenService {

    protected static final long MILLIS_SECOND = 1000;

    private final static long EXPIRE_TIME = CacheConstants.TOKEN_EXPIRE * 60;

    private final RedisService redisService;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        // 生成token
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        loginUser.setUserId(loginUser.getSysUser().getUserId());
        loginUser.setUsername(loginUser.getSysUser().getUserName());
        loginUser.setIpaddr(ServletUtil.getClientIP(Objects.requireNonNull(ServletUtils.getRequest())));

        // 删除之前的该用户token
        String oldToken = redisService.getCacheMapValue("USER_TOKEN", loginUser.getUserId());
        delLoginUser(oldToken);

        // 保存或更新用户token
        redisService.setCacheMapValue("USER_TOKEN", loginUser.getUserId(), token);
        refreshToken(loginUser);

        Map<String, Object> map = new HashMap<>(2);
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        return map;
    }

    public void delLoginUser(String token) {
        if (StrUtil.isNotEmpty(token)) {
            String userKey = CacheConstants.getCacheKey(CacheConstants.LOGIN_TOKEN_KEY, token);
            redisService.deleteObject(userKey);
        }
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (BeanUtil.isNotEmpty(loginUser) && StrUtil.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
        // 根据uuid将loginUser缓存
        String userKey = CacheConstants.getCacheKey(CacheConstants.LOGIN_TOKEN_KEY, loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    private LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            String userKey = CacheConstants.getCacheKey(CacheConstants.LOGIN_TOKEN_KEY, token);
            return redisService.getCacheObject(userKey);
        }
        return null;
    }

}